package com.my.pdfexplorer.fragments;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.my.pdfexplorer.BaseActivity;


public class BaseFragment<T extends ViewBinding> extends Fragment {
    public static final String POSITION_KEY = "position_key";

    private BaseActivity baseActivity;
    public Handler handler = null;
    public T viewBinding = null;

    private int position = -1;
    public boolean isCreate = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle bundle = getArguments();
        if (bundle != null) {
            position = bundle.getInt(POSITION_KEY);
        }
        if (context instanceof BaseActivity) {
            baseActivity = (BaseActivity) context;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getViewBinder() != null) {
            viewBinding = getViewBinder();
            isCreate = true;
            return viewBinding.getRoot();
        }
        return null;
    }

    protected T getViewBinder() {
        return null;
    }

    public BaseActivity getBaseActivity() {
        if (baseActivity == null) {
            throw new IllegalArgumentException("the acticity must be extends BaseActivity");
        }
        return baseActivity;
    }

    /***
     * 包含了onCreateView里面需要的所有的初始化操作
     */
    protected void initAll() {
        initHandler();
        initUi();
        initConfigUi();
        initHttp();
        initOther();
    }


    /***
     * 对父类中handler的初始化
     */
    protected void initHandler() {

    }

    /***
     * 规范UI元素的初始化
     */
    protected void initUi() {

    }

    /***
     * 配置ui参数如点击事件等的初始化
     */
    protected void initConfigUi() {

    }


    /***
     * 一些http请求的初始化
     */
    protected void initHttp() {

    }

    /***
     * 初始化其余的内容如开启线程控制activity的跳转等
     */
    protected void initOther() {
    }

    public int getPosition() {
        return position;
    }


    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}
